﻿using AutoMapper;
using Equipment.API.DTOs.RequestDto.DefectlocationListRequest;
using Equipment.API.DTOs.ResponseDto.DefectlocationResponse;
using Equipment.Domain.Detectionmethod;
using Equipment.Errorcode;
using Equipment.Errorcode.ErrorCode;
using Equipment.Infrastructure.Interfaces;
using Equipment.Infrastructure.Repositories;
using Microsoft.EntityFrameworkCore;
using Serilog;
using System.ComponentModel.DataAnnotations;

namespace Equipment.API.Application.Service.DetectionmethodService
{
    /// <summary>
    /// 缺陷等级信息服务层
    /// </summary>
    public class DefectgradeService
    {
        private readonly IDefectgradeRepository   _defectgradeRepository;

        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="defectgradeRepository"></param>
        /// <param name="mapper"></param>
        public DefectgradeService(IDefectgradeRepository defectgradeRepository, IMapper mapper)
        {
            _defectgradeRepository = defectgradeRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取缺陷等级下拉列表
        /// </summary>
        /// <returns></returns>
        public async Task<ApiResult> GetDefectgradeDropdown()
        {
            var result = await _defectgradeRepository.GetAllAsync();
            // 映射为DTO并返回
            var resultDto = _mapper.Map<List<DefectgradeDropdownResponseDto>>(result);
            return ApiResult.Ok(resultDto, "缺陷等级下拉列表显示！");
        }

        /// <summary>
        /// 缺陷等级信息添加成功
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddDefectgrade(AddDefectgradeResponseDto param)
        {
            var result = _mapper.Map<Defectgrade>(param);

            var defegrade = await _defectgradeRepository.InsertAsync(result);

            return ApiResult.Ok(defegrade,"缺陷等级信息添加成功");
        }
        /// <summary>
        /// 获取缺陷等级列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> GetDefectgrades(GetDefectgradeRequestDto dto, int pageNumber = 1, int pageSize = 2)
        {
            try
            {
                Log.Information("开始查询缺陷等级列表：{@Request}", dto);

                var query = (await _defectgradeRepository.GetAllAsync(a => a.Isdelete == false)).AsQueryable();
                //  按缺陷等级名称模糊查询
                //  按缺陷等级编码模糊查询
                if (!string.IsNullOrEmpty(dto.Lvencodingname))
                {
                    query = query.Where(a => a.Lvname.Contains(dto.Lvencodingname) || a.Lvencoding.Contains(dto.Lvencodingname));
                }
                // 按缺陷等级状态查询
                if (dto.Lvstatus != null)
                {
                    query = query.Where(a => a.Lvstatus == dto.Lvstatus);
                }
                // 3. 映射为DTO并保持IQueryable特性
                var projectedQuery = _mapper.ProjectTo<GetDefecttypeResponseDto>(query);

                var pageResult = PaginationHelper.Paginate(projectedQuery, pageNumber, pageSize);
                return ApiResult.Ok(pageResult, "缺陷等级列表显示！");
            }
            catch (AutoMapperMappingException ex)
            {
                Log.Error(ex, "数据映射异常：{Message}", ex.Message);
                return ApiResult.Fail("数据转换错误");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "查询缺陷等级列表异常");
                return ApiResult.Fail("系统错误，查询失败");
            }
        }

        /// <summary>
        /// 更新缺陷等级信息
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ApiResult> UpdateDefectgrade(UpdateDefectgradeRequestDto param)
        {
            try
            {
                Log.Information("开始更新缺陷等级：{@RequestData}", param);

                // 1. 参数基础校验
                if (param == null)
                {
                    Log.Warning("更新请求参数为空");
                    return ApiResult.Fail("请求参数不能为空");
                }

                // 3. 检查实体是否存在
                var existingEntity = await _defectgradeRepository.GetAsync(d => d.Defectgradeid == param.Defectgradeid);
                if (existingEntity == null)
                {
                    Log.Warning("指定的缺陷等级不存在：{Defectgradeid}", param.Defectgradeid);
                    return ApiResult.Fail("指定的缺陷等级不存在");
                }

                // 5. 执行数据映射与更新
                _mapper.Map(param, existingEntity); // 保持现有实体引用

                // 6. 持久化操作
                var updatedEntity = await _defectgradeRepository.UpdateAsync(existingEntity);

                Log.Information("缺陷等级更新成功：{Defectgradeid}", param.Defectgradeid);
                return ApiResult.Ok(updatedEntity, "缺陷等级更新成功");
            }
            catch (DbUpdateConcurrencyException ex)
            {
                Log.Error(ex, "并发更新冲突：{Defectgradeid}", param?.Defectgradeid);
                return ApiResult.Fail("数据已被其他用户修改，请刷新后重试");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "更新缺陷等级异常：{Defectgradeid}", param?.Defectgradeid);
                return ApiResult.Fail("系统错误，更新操作失败");
            }
        }

        /// <summary>
        /// 删除缺陷等级信息（软删除）
        /// </summary>
        public async Task<ApiResult> DeleteDefectgrade(int Defectgradeid)
        {
            try
            {
                Log.Information("删除缺陷等级信息：{DefectGradeId}", Defectgradeid);

                // 获取实体
                var defectGrade = await _defectgradeRepository.GetAsync(d => d.Defectgradeid == Defectgradeid);
                if (defectGrade == null)
                {
                    return ApiResult.Fail("缺陷等级信息不存在");
                }

                // 执行软删除
                defectGrade.Isdelete = true;
                // 若仓储层需要显式更新
                await _defectgradeRepository.UpdateAsync(defectGrade);

                // 返回简洁的成功响应
                return ApiResult.Ok(defectGrade,"缺陷等级删除成功");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "删除缺陷等级信息异常：{DefectGradeId}", Defectgradeid);
                return ApiResult.Fail("系统错误，删除操作失败"); // 统一错误响应
            }
        }



    }
}
